package com.atguigu.serviceedu.controller.site;

import com.atguigu.exception.Guliexception;
import com.atguigu.serviceedu.utills.UcenterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
@CrossOrigin
@RequestMapping("/site/wx")
public class SiteWxController {
    @Autowired
    private UcenterProperties ucenterProperties;
    @GetMapping("login")
    String getQrConnect(HttpSession session){
        // https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE
        String baseUrl="https://open.weixin.qq.com/connect/qrconnect?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s"+
                "#wechat_redirect";
        String redirect_uri="";
        try {
            redirect_uri= URLEncoder.encode(ucenterProperties.getRedirectUri(),"UTF-8");
        }catch (Exception e){
            throw new Guliexception(20001,"编码异常!");
        }
        String state= UUID.randomUUID().toString();
        session.setAttribute("wx_state",state);
        String url=String.format(baseUrl,ucenterProperties.getAppId(),redirect_uri,state);//这个函数，就是给baseurl%s占位符赋值
        return "redirect:" + url;//这个字符串返回给浏览器后，浏览器自己不得不重新发请求到url处。
    }
}
